<?php

/* 二维数组根据某个字段排序 */
function array_sort(array $array, string $keys, $sort = "desc"): array
{
	$order	= $sort === 'asc' ? SORT_ASC : SORT_DESC;
	$keysValue = [];
	foreach ($array as $key => $value) {
		$keysValue[$key] = $value[$keys];
	}
	array_multisort($keysValue, $order, $array);
	return $array;
}


/* 菜单父子序列化 */
function get_system_menus()
{
	if (get_cache('menu' . get_login_admin('id'))) {
        $list = get_cache('menu' . get_login_admin('id'));
    } else {
        $adminGroup = \think\facade\Db::name('AdminGroupAccess')->where(['uid' => get_login_admin('id')])->column('group_id');
        $adminMenu = \think\facade\Db::name('AdminGroup')->where('id', 'in', $adminGroup)->column('menus');
        $adminMenus = [];
        foreach ($adminMenu as $k => $v) {
            $v = explode(',', $v);
            $adminMenus = array_merge($adminMenus, $v);
        }
        $menu = \think\facade\Db::name('AdminMenu')->where('id', 'in', $adminMenus)->order('sort asc')->select()->toArray();
        $list = list_to_tree($menu);
        \think\facade\Cache::tag('adminMenu')->set('menu' . get_login_admin('id'), $list);
    }
    return $list;
}

/* list to tree */
function list_to_tree ($list, $pk = 'id', $pid = 'pid', $child = 'list', $root = 0)
{
	$tree = array();
	if (is_array($list)) {
		// 创建基于主键的数组引用
		$primary = array();
		foreach ($list as $key => $data) {
			$primary[$data[$pk]] = &$list[$key];
		}
		foreach ($list as $key => $data) {
			// 判断是否存在父级
			$parentId = $data[$pid];
			if ($root == $parentId) {
				$tree[$data[$pk]] = &$list[$key];
			} else {
				if (isset($primary[$parentId])) {
					$parent = &$primary[$parentId];
					$parent[$child][$data[$pk]] = &$list[$key];
				}
			}
		}
	}
	return $tree;
}



/* 返回 layui table 数据格式 */
function table_data ($code = 0, $msg = "请求成功", $data = [], $httpStatus = 200, $header = [], $options = [])
{
	$res['code'] = $code;
	$res['msg'] = $msg;
	if (is_object($data)) {
		$data = $data->toArray();
	}
	if (!empty($data['total'])) {
		$res['count'] = $data['total'];
	} else {
		$res['count'] = 0;
	}
	$res['data'] = $data['data'];
	$response = \think\Response::create($res, "json", $httpStatus, $header, $options);
	throw new \think\exception\HttpResponseException($response);
}